const {sqlList, sqlTotal, sqlRows, sqlDelete, save, sqlUpdate, sqlTableDel, sqlSaveList, sqlArrList, sqlIdDel} = require("../../sql/rows");
const role = require("express").Router()
const {rules, valid} = require("../../utils/rules")
const handlerList = require("../../handler/handlerList");
const {loggers} = require("winston");
const nanoid = require("nanoid").nanoid

const roleSave = [
    {
        name: "roleName",
        message: "角色名称"
    },

    {
        name: "status",
        message: "角色状态"
    },
    {
        name: "role_order",
        message: "角色排序"
    },
]

const roleUpdate = [].concat(roleSave, [
    {
        name: "roleId",
        message: "角色id"
    },
])
// 添加
role.post("/save", rules(roleSave), valid, async (req, res) => {
    try {
        // const role = await req.db.query(`SELECT * FROM ums_role WHERE roleId = '${req.body.roleId}' OR roleName = '${req.body.roleName}'`)
        const data = {
            ...req.body,
            roleId: nanoid()
        }
        const role = await req.db.query(sqlRows('ums_role', {data: {roleName: req.body.roleName}}))
        if (role.length) {
            return res.status(200).send({
                code: 400,
                message: '名称或者字符重复',
                data: ''
            })
        }
        await req.db.query(save('ums_role', data))
        return res.status(200).send({
            code: 200,
            message: '添加成功',
            data: ''
        })
    } catch (e) {
        console.log(e)
        return res.status(500).send({
            code: 500,
            message: '系统错误',
            data: ''
        })
    }
})
// 编辑
role.post("/update", rules(roleUpdate), valid, async (req, res) => {
    try {
        const {role_order,status, roleName, roleId} = req.body
        const data = {
            status,
            role_order,
            roleName
        }
        const sql = sqlUpdate('ums_role', {
            data,
            key: {roleId}
        })
        await req.db.query(sql)
        return res.status(200).send({
            code: 200,
            message: "修改成功",
            data: ""
        })
    } catch (e) {
        return res.status(500).send({
            code: 200,
            message: '系统错误',
            data: ''
        })
    }
})
// 删除
role.delete("/delete", async (req, res) => {
    try {
        if (req.query.roleId){
            const roleId = req.query.roleId
            const roles = await req.db.query(sqlRows('ums_role', {data: {roleId}}))
            if (roles.length){
                const data = {
                    roleId
                }
                await req.db.query(sqlDelete('ums_role_or_menu', {data}))
                await req.db.query(sqlDelete('ums_role_or_user', {data}))
                await req.db.query(sqlDelete('ums_role', {data}))
                return res.status(200).send({
                    code: 200,
                    data: "",
                    message: "删除成功"
                })
            }
            return res.status(200).send({
                code: 400,
                message: '删除错误没有当前值',
                data: ''
            })
        }
        return res.status(200).send({
            code: 400,
            message: '请传入ID',
            data: ''
        })
    }catch (e) {
        return res.status(500).send({
            code: 200,
            message: '系统错误',
            data: ''
        })
    }
})
// 查询
role.post("/list", async (req, res) => handlerList(req, res, 'ums_role'))
// 状态修改
role.post("/status", async (req, res) => {
    try {
        const {
            status,
            roleId
        } = req.body
        const data = {
            status
        }
        const sql = sqlUpdate('ums_role', {data, key:{roleId}})
        await req.db.query(sql)
        return res.status(200).send({
            code: 200,
            message: '状态修改成功',
            data: ''
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: '系统错误',
            data: ''
        })
    }
})
// 用户授权
role.post("/userImpower", async (req, res) => {
    try {
        const {list, roleId} = req.body

        const del = sqlIdDel('ums_role_or_user', {roleId})
        await req.db.query(del)

        const data = list.map(item => ({userId: item.userId}))
        await req.db.query(sqlIdDel('ums_role_or_user', data))

        const sql = sqlSaveList('ums_role_or_user', list)
        await req.db.query(sql)

        return res.status(200).send({
            code: 200,
            message: '授权成功',
            data: ''
        })
    } catch (e) {
        console.log(e)
        return res.status(500).send({
            code: 500,
            message: '系统错误',
            data: ''
        })
    }
})
// 根据角色查询所有已授权用户
role.get("/userList", async (req, res) => {
    try {
        const data = req.query
        const sql = sqlRows('ums_role_or_user', {data, SELECT: 'userId'})
        const roleUsers = await req.db.query(sql)
        const arr = []
        if (roleUsers.length) {
            const arrSql = sqlArrList('ums_user',{
                key: 'userId',
                tableKey: 'id',
                list: roleUsers
            })
            const users = await req.db.query(arrSql)
            arr.push(...users)
        }
        // console.log(arr)
        return res.status(200).send({
            code: 200,
            message: '',
            data: arr
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: '系统错误',
            data: ''
        })
    }
})
// 菜单授权
role.post("/menuImpower", async (req, res) => {
    try {
        const {list, roleId} = req.body
        // console.log(list)
        // 根据角色id删除 当前表中的数据
        const del = sqlIdDel('ums_role_or_menu', {roleId})
        await req.db.query(del)
        //
        // // const data = list.map(item => ({userId: item.userId}))
        // // await req.db.query(sqlIdDel('ums_role_or_user', data))
        //
        const sql = sqlSaveList('ums_role_or_menu', list)
        await req.db.query(sql)

        return res.status(200).send({
            code: 200,
            message: '授权成功',
            data: ''
        })
    } catch (e) {
        console.log(e)
        return res.status(500).send({
            code: 500,
            message: '系统错误',
            data: ''
        })
    }
})
// 根据角色查询所有已授权菜单
role.get("/menuList", async (req, res) => {
    try {
        const sql = sqlRows('ums_role_or_menu', {
            data: req.query,
            SELECT: 'menuId'
        })
        const menus = await req.db.query(sql)
        const arr = []
        if (menus.length) {
            arr.push(...menus.map(item => item.menuId))
        }
        return res.status(200).send({
            code: 200,
            message: '',
            data: arr
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: '系统错误',
            data: ''
        })
    }
})

module.exports = role
